var mongoose = require('mongoose');
var Upload = require('../models/upload.model')// 引数据模型
var multer  = require('multer');
var path =require('path');
var fs=require('fs');

exports.img = function(req,res,next){//新增图片
    //设置对象
    var storage = multer.diskStorage({  
        destination: function (req, file, cb) {
        cb(null, './uploads')
        },
        filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now()+ path.extname(file.originalname))
        }
    })

    var uploadImg=multer({
		storage: storage,
		fileFilter:function(req,file,callback){
			var ext =path.extname(file.originalname);
			if(ext!=='.png' && ext!=='.jpg' && ext!=='.gif' && ext!=='.jpeg'){
				return callback(res.end('文件类型不符合'));
			}
			callback(null,true);
		}
	}).single('avatar')
	uploadImg(req,res,function(err){
        console.log(req.file);
        res.json(req.file);
		//res.end('file uploaded');
	}) 
}

// 新增
exports.create = function(req,res,next){
    var upload= new Upload(req.body);
    upload.save()
    .then(data=>{
        res.json(data)
    })
    
}

//修改
exports.update = function(req,res,next){
    
      var id = req.params.id; // req.param('id')
      // 现在操作的都是mongoose而不是mongodb
      Upload.findByIdAndUpdate(id,{$set: req.body}, {new:false} )
      .then(data=>{
          //res.json({msg:'数据修改成功',status:200}); // 如果你要返回数据，这个data返回的是你之前修改的那个数据内容
          res.json(data);
      })
  }
  
  //删除
  exports.remove = function(req,res,next){
      var id = req.body.id;
      Upload.findByIdAndRemove(id,function(err,doc){
          res.json({msg:'数据删除成功',status:200})
      })
      var filepath='./uploads/'+req.body.filename;
      fs.unlink(filepath,function(err){
          if(err){
              console.log(err);
          }
          else{
              console.log(filepath+'文件删除成功');
          }
      })
  }
  

  exports.list = function(req,res,next){
      var page = (req.body.page) ? req.body.page : 1;
      var rows = (req.body.limit) ? req.body.limit : 5;
  
      var queryCondition = {};
      var filename;
      if( req.body.filename && req.body.filename.trim().length>0 ){
        filename = req.body.filename;
          queryCondition = {"filename":new RegExp(filename,'i')}
      }
      if( req.body.cateId && req.body.cateId.trim().length>0){
          cateId=req.body.cateId;
          Object.assign(queryCondition,{"cateId":cateId})
      }
  
      Upload.paginate(queryCondition, { page: parseInt(page), limit: parseInt(rows) }, function(err, result) {
          result.rows = result.docs;
          delete result.docs;
  
         res.json(result)
      });
  }